#include <stdio.h>
#include <typeinfo>
#include "engine.h"
#include "gamestate.h"

void CEngine::Init(const char* title, int width, int height, int bpp, int framerate, bool fullscreen, bool debug) {
	int flags = sf::Style::Resize | sf::Style::Close;

	if(fullscreen)
		flags = sf::Style::Fullscreen;

	window.Create(sf::VideoMode(width, height, bpp), title, flags);
	//window.SetFramerateLimit(framerate);

	window.Clear(sf::Color(0, 0, 0));
	window.Display();

	this->fullscreen = fullscreen;
	this->running = true;
	this->debug = true;

	debugText = new sf::String();
	debugText->SetY(580.f);
	debugText->SetSize(15.f);
	debugText->SetColor(sf::Color(255, 170, 0));


	printf("Engine init");
}

void CEngine::Cleanup() {
	window.Close();

	printf("Engine cleanup");
}

void CEngine::ChangeState(CGameState* state) 
{
	strcpy(curState, typeid(*states.back()).name());

	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

void CEngine::PushState(CGameState* state)
{
	// pause current state
	if ( !states.empty() ) {
		states.back()->Pause();
	}

	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

void CEngine::PopState()
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}

	// resume previous state
	if ( !states.empty() ) {
		states.back()->Resume();
	}
}

void CEngine::HandleEvents() 
{
	// let the state handle events
	states.back()->HandleEvents(this);
}

void CEngine::Update() 
{
	// let the state update the game
	states.back()->Update(this);
}

void CEngine::Draw() 
{
	window.Clear();

	//let the state draw the screen
	states.back()->Draw(this);

	if(debug) {
		// Create a graphical string
		char str[50] = "";
		sprintf_s(str, "FPS: %d", curFramerate);
		debugText->SetText(str);
		debugText->SetX(725.f);
		window.Draw(*debugText);

		sprintf_s(str, "Logic: %d", curFrequency);
		debugText->SetText(str);
		debugText->SetX(645.f);
		window.Draw(*debugText);

		sprintf_s(str, "Current State: %s", curState);
		debugText->SetText(str);
		debugText->SetX(15.f);
		window.Draw(*debugText);

		window.Display();
	}
}